package com.yuebao.controller;

import com.yuebao.api.PaymentService;

import com.yuebao.exception.CustomerException;
import com.yuebao.model.pojo.Transaction;
import com.yuebao.model.vo.PayAsynDTO;
import com.yuebao.request.RequestParameter;
import com.yuebao.result.EntityResponse;
import com.yuebao.service.impl.AlipayClientService;

import com.yuebao.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

import static com.yuebao.enumeration.ResponseCodeEnum.FORBIDDEN;
import static com.yuebao.enumeration.ResponseCodeEnum.SUCCESS;

@Slf4j
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Resource
    private PaymentService paymentService;
    
    @Resource
    private AlipayClientService alipayClientService;
    
    @PostMapping("/pay")
    public EntityResponse<String> handlePayment(@RequestBody @Valid RequestParameter<Transaction> transaction)  {
        log.info("进入Payment===>handlePayment的param{}",transaction);
        String form = "";
        try{
            form = alipayClientService.sentToPayAndGetForm(transaction.getBody());
        }catch (CustomerException e){
            log.error("支付错误--》{}",e.getMsg());
            return new EntityResponse<>(FORBIDDEN,e.getMsg(),form);
        }
        log.info("支付成功==》{}",form);
        return new EntityResponse<>(SUCCESS,"成功",form) ;
    }

    @PostMapping("/payed/notify")
    public String handleAlipayed(@RequestBody PayAsynDTO vo)  {
        log.info("支付宝回调：{}", JsonUtils.writeValueAsString(vo));
        try {
            paymentService.handlePaymentResult(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }

        return "success";
    }
}
